package pl.edu.pw.ee.buildcity.notifiers.preparators;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.tools.generic.DateTool;
import org.apache.velocity.tools.generic.ListTool;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;
import pl.edu.pw.ee.buildcity.entities.BuildActivity;

import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

/**
 * Prepares email message based on template for build notifications emails.
 * Returned email is ready to be send to client.
 */
public class BuildNotificationPreparator implements MimeMessagePreparator {

	private static final String BUILD_NOTIFIER_EMAIL = "buildcitynotifier@gmail.com";

	private static final String SUBJECT_TEMPLATE = "build-notification-mail-subject-template.vm";
	private static final String BODY_TEMPLATE = "build-notification-mail-body-template.vm";

	private static final boolean FORCE_HTML_EMAIL_FORMAT = true;

	private BuildActivity buildActivity;
	private String recipient;
	private VelocityEngine velocityEngine;

	public BuildNotificationPreparator(BuildActivity buildActivity, VelocityEngine velocityEngine) {
		this.buildActivity = buildActivity;
		this.velocityEngine = velocityEngine;
	}

	public void specifyRecipient(String recipient) {
		this.recipient = recipient;
	}

	@Override
	public void prepare(MimeMessage mimeMessage) throws Exception {
		MimeMessageHelper email = new MimeMessageHelper(mimeMessage);
		email.setTo(recipient);
		email.setFrom(BUILD_NOTIFIER_EMAIL);
		Map model = createModel();
		email.setText(fillTemplate(BODY_TEMPLATE, model), FORCE_HTML_EMAIL_FORMAT); //true means 'force html'
		email.setSubject(fillTemplate(SUBJECT_TEMPLATE, model));
	}

	private Map createModel() {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("formatter", new DateTool()); //to format dates in template...
		model.put("lists", new ListTool()); //to check if commits list is empty...
		model.put("buildActivity", buildActivity);
		return model;
	}

	private String fillTemplate(String templateFileName, Map<String, Object> model) {
		String mergedTemplate = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateFileName, model);
		return mergedTemplate;
	}

	@Override
	public String toString() {
		return "recipient: " + recipient + ", buildActivity: " + buildActivity;
	}
}